import { defineStore } from "pinia";
import { ref, Ref } from "vue";
import dayjs from "dayjs";
import { useConfigStore } from './configStore'

export interface Count {
  count: number
  max: number
}

interface CountMap {
  [key: string]: Count
}

export const useCountStore = defineStore('count', () => {
  // 历史统计数
  const countMap: Ref<CountMap> = ref({})

  const getCount = () => {
    const day = dayjs().format('YYYY-MM-DD')
    const countItem = countMap.value[day]
    if (countItem) {
      return countItem.count
    }
    return 0
  }

  const getTodayCountInfo = () => {
    const day = dayjs().format('YYYY-MM-DD')
    const countItem = countMap.value[day]
    if (countItem) {
      return {
        key: day,
        count: countItem
      }
    }else{
      setCount(0)
      const countItem = countMap.value[day]
      return {
        key: day,
        count: countItem
      }
    }
  }

  const setCount = (count: number) => {
    const day = dayjs().format('YYYY-MM-DD')
    const countItem = countMap.value[day]
    if (countItem) {
      countItem.count = count
    } else {
      const configStore = useConfigStore()
      countMap.value[day] = {
        count,
        max: configStore.config.max
      }
    }
  }

  const addCount = () => {
    const day = dayjs().format('YYYY-MM-DD')
    const countItem = countMap.value[day]
    let count = 0
    if (!countItem) {
      saveBeforeCountInfo()
    } else {
      count = countItem.count
    }
    const configStore = useConfigStore()
    setCount(count + configStore.config.step)
  }

  const resetCount = () => {
    const count = getCount()
    if (count === 0) return
    setCount(0)
  }

  const resetOneStep = () => {
    const count = getCount()
    if (count === 0) return
    const configStore = useConfigStore()
    console.log(count, configStore.config.step)
    setCount(count - configStore.config.step)
  }

  // 保存之前的统计信息
  const saveBeforeCountInfo = () => {
    const day = dayjs().format('YYYY-MM-DD')
    const beforeCount = Object.keys(countMap.value).filter(key => key !== day)
    for (const key of beforeCount) {
      const countItem = countMap.value[key]
      if(countItem){
        window.api.saveInfo(key, { ...countItem })
      }
      delete countMap.value[key]
    }
  }

  // 保存昨天的统计信息并重置
  const saveYesterdayCountInfo = () => {
    resetCount()
    saveBeforeCountInfo()
  }

  return {
    countMap,
    getCount,
    setCount,
    addCount,
    resetCount,
    saveBeforeCountInfo,
    resetOneStep,
    getTodayCountInfo,
    saveYesterdayCountInfo
  }
}, {
  persist: true
})
